javascript:(function(){
	//begin unframe code
	if (navigator.appName == 'Microsoft Internet Explorer') {
		alert('You are using Internet Explorer, this bookmarklet will not work.\nUse Firefox or Chrome instead.');
		return;
	}
	if (/m.mafiawars.com/.test(document.location)) {
		window.location.href = document.location+'?iframe=1';
	}
	else if (/apps.facebook.com.inthemafia/.test(document.location)) {
		//Credits to Christopher(?) for this new fix
		for (var i = 0; i < document.forms.length; i++) {
			if (/canvas_iframe_post/.test(document.forms[i].id) && document.forms[i].target == "mafiawars") {
				document.forms[i].target = '';
				document.forms[i].submit();
				return;
			}
		}
	}
	else if (document.getElementById('some_mwiframe')) {
		// new mafiawars.com iframe
		window.location.href = document.getElementById('some_mwiframe').src;
		return;
	}
	else {
		document.body.parentNode.style.overflowY = "scroll";
		document.body.style.overflowX = "auto";
		document.body.style.overflowY = "auto";
		try {
			document.evaluate('//div[@id="mw_city_wrapper"]/div', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).style.margin = "auto";
			if (typeof FB != 'undefined') {
				FB.CanvasClient.stopTimerToSizeToContent;
				window.clearInterval(FB.CanvasClient._timer);
				FB.CanvasClient._timer = -1;
			}
			document.getElementById('snapi_zbar').parentNode.parentNode.removeChild(document.getElementById('snapi_zbar').parentNode);

		} catch (fberr) {}
		//Revolving Revolver of Death from Arun, http://arun.keen-computing.co.uk/?page_id=33
		$('#LoadingBackground').hide();
		$('#LoadingOverlay').hide();
		$('#LoadingRefresh').hide();
	}
	//end unframe code

	//hack to kill the resizer calls
	iframeResizePipe = function() {};
//begin the sloppy code
//only read on if you are tolerant to bad coding :)
//this is a early experimental release

//URLDecode from http://www.albionresearch.com/misc/urlencode.php
function URLDecode(encoded) {
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   var pausemsg = '';
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};
// URLDecode END

// from Yevgen Silant'yev, http://joyka.pp.ua/
function getMWURL() {
	str = document.location;
	str = str.toString();
	beg = str.substring(0,str.indexOf('?')+1);
	str = str.substring(str.indexOf('?')+1);
	str = str.split('&');
	mid = '';
	for(var i=0;i<str.length;i++){
		if(str[i].indexOf('sf_xw_')==0){ mid=mid+str[i]+'&'; }
	}
	return beg+mid;
}

var MWURL = getMWURL();
var content = document.getElementById('popup_fodder');
var output = '';
var version = 'Buy Properties v1.06 beta';
// try { var propvars = URLDecode(document.getElementsByName('flashvars')[0].value); }
// catch (properr) { 
	// alert('Some error occured!\n'+version+' not loaded.\n\nBookmarklet needs to be run on a flash-enabled property page.');
	// return; 
// }
var run = 0;
var wait1 = 3;
var wait2 = 5;
var props = [];
var levels = [];
var properties;
var object = {};
var money = 0;
var success = true;
reload_params();
var currentPageCount = 1;
var cashonhand = /([\d,]+)/.exec(document.getElementsByClassName('cur_stats cur_cash')[0].innerHTML)[1].replace(/,/g,'');
var failed = 0;
var config_html = 
'<style type="text/css">' + 
        '.messages img{margin:0 3px;vertical-align:top};'+ 
        '#close{display:inline};'+ 
'</style>'+ 
'<table class="messages">'+
        '<tr><td colspan="4" align="right" style="text-align:right;font-size:0.9em">' + version + ' - Visit <a href="http://www.spockholm.com/mafia/bookmarklets.php?BuyProperties" target="_top">Spockholm Mafia Tools</a> - <a href="http://www.spockholm.com/mafia/donate.php">Donate a Pint</a> - <a href="#" id="close"><img src="http://www.spockholm.com/mafia/stop.gif" title="Close" width="16" height="16"></a></td></tr>' + 
'<tr><td>Delay interval:</td><td colspan="3"><input type="text" name="wait1" id="wait1" value="'+wait1+'" size="3">-<input type="text" name="wait2" id="wait2" value="'+wait2+'" size="3"> Delay in seconds between buys.</td></tr>' +
'<tr><td>Status:</td><td colspan="3" id="status"></td></tr>'+
'<tr><td colspan="4"><hr /></td></tr>'+
'<tr><td><strong>Property:</strong></td><td><strong>Level/Max:</strong></td><td><strong>Upgrade to:</strong></td><td><strong>Cost:</strong></td></tr>';

for (x in object) {
	//name level payout rate build_cost upgrade_cost property_pic last_collected percent_collectable buy_url collect_url maxlevel city type
	config_html += 
	'<tr><td width=150>'+object[x]['name']+'</td>'+
	'<td><span id="proplvl'+x+'">'+object[x]['level']+'</span>/'+object[x]['maxlevel']+'</td>'+
	'<td><input type="text" name="prop" id="prop'+x+'" value="'+object[x]['level']+'" size="6" maxlength="6"/></td>'+
	'<td><span id="cost'+x+'" name="cost"></span></td></tr>\n';
}

config_html += 
'<tr><td colspan="3"><strong>Money spent:</strong> <span id="money" class="good"></span></td><td><strong>Total:</strong> <span id="total" class="good"></span> <span id="missing" class="bad"></span></td></tr>'+
'<tr><td colspan="4"><span id="log"></span></td></tr>'+
'<tr><td colspan="4"><span id="action"><a class="sexy_button" id="start">Start</a></span></td></tr>'+
'</table>';

function create_div() {
	if (document.getElementById('spockdiv')) {
		document.getElementById('spockdiv').innerHTML = config_html;
	}
	else {
		var spock_div = document.createElement("div");
		spock_div.id = 'spockdiv';
		spock_div.innerHTML = config_html;
		content.insertBefore(spock_div, content.firstChild);
	}
	props=document.getElementsByName('prop');
	for (i=0;i<props.length;i++) {
		var theid = props[i].id.substr(4);
		document.getElementById('prop'+theid).onkeyup=function(e) {
			var currlevel = object[this.id.substr(4)]['level'];
			var newlevel;
			if (newlevel != this.value) {
				newlevel = this.value;
				document.getElementById('cost'+this.id.substr(4)).innerHTML = '$'+commas(property_cost(currlevel,newlevel,object[this.id.substr(4)]['upgrade_cost'],object[this.id.substr(4)]['build_cost']));
				total_cost();
			}
		};	
	}
}

create_div();
function property_cost(currlev,newlev,upgradecost,buildcost) {
	var cost = 0;
	for (i=currlev; i<newlev; i++) {
		cost += parseInt(buildcost+upgradecost*i);
	}
	return cost;
}
function total_cost() {
	var thecosts = document.getElementsByName('cost');
	var costs = 0;
	for(var i=0; i<thecosts.length; i++){
		var price = thecosts[i].innerHTML.replace(/[$,]/g, '');
		if (price > 0) {
			costs+=parseInt(price);
		}
	}
	if (costs > cashonhand)	{
		var missing = parseInt(costs-cashonhand);
		document.getElementById('total').innerHTML = '$'+commas(costs);
		document.getElementById('missing').innerHTML = 'Missing: $'+commas(missing)
	}
	else {
		document.getElementById('total').innerHTML = '$'+commas(costs);
		document.getElementById('missing').innerHTML = '';
	}
}
function close() {
	run = 0;
	content.removeChild(document.getElementById("spockdiv"));
	return false;
}
document.getElementById('close').onclick = close;
document.getElementById('wait1').onkeyup=function(e) {
	time = parseInt(document.getElementById('wait1').value);
	if((time < 0) || (!time)) { wait1 = 0; }
	else { wait1 = time; }
	document.getElementById('wait1').value=wait1;
}
document.getElementById('wait2').onkeyup=function(e) {
	time = parseInt(document.getElementById('wait2').value);
	if((time < 0) || (!time)) { wait2 = 5; }
	else { wait2 = time; }
	//createCookie('spockaX_wait2',wait2);
	document.getElementById('wait2').value=wait2;
}
function msg(s) {
    document.getElementById('status').innerHTML = s;
}
function log(s) {
	var l=document.getElementById('log');
	if (s) {
		l.innerHTML=s+'<br />'+l.innerHTML;
	}
}
function commas(s) {
	while (d=/(\d+)(\d{3}.*)/.exec(s)) {
		s = d[1] + ',' + d[2];
	}
	return s;
}
function timestamp() {
	now = new Date();
	var CurH = now.getHours();
	CurH = (CurH<10?'0'+CurH:CurH);
	var CurM = now.getMinutes();
	CurM = (CurM<10?'0'+CurM:CurM);
	return '<span class="more_in">['+CurH+':'+CurM+']</span> ';
}
function reload_params() {
	var flashvars = document.getElementsByName('flashvars');
	for(i=0;i<flashvars.length;i++) {
		if(/mw_data/.test(flashvars[i].value)) {
			//var propvars = URLDecode(document.getElementsByName('flashvars')[i].value);
			//var propvars = document.getElementsByName('flashvars')[i].value;
			var propvars = /mw_data=%5B(.*)%5D/.exec(document.getElementsByName('flashvars')[i].value)[1];
			propvars = URLDecode(propvars);
			//prompt('Propvars',propvars);
			//object = eval("("+/mw_data=(.*?)&mw/.exec(propvars)[1]+")");
			//object = eval("("+/mw_data=%5B(.*)%5D/.exec(propvars)[1]+")");
			object = jQuery.parseJSON('['+propvars+']');
			var success = true;
		}
	}
	if (!success) {
		if(failed > 5) {
			alert(version+'\nCould not load property variables, tried 5 times, I am really tired now...\nTry reloading the game.\n\n Bookmarklet does not work in Vegas/Italy/Brazil!');
			return;
		}
		failed++;
		if (!document.getElementById('status')) {
			alert(version+'\nCould not load property variables. Try reloading the game.\n\n Bookmarklet does not work in Vegas/Italy/Brazil!!');
			msg('make bookmarklet fail in a crude and dirty way');
			return;
		}
		msg('Could not load property variables, attempting to reload properties page in 5 seconds...');
		setTimeout(function(){
			document.getElementById('inner_page').addEventListener('DOMSubtreeModified',state_change,false);	
			do_ajax('inner_page', 'remote/html_server.php?xw_controller=propertyV2&xw_action=view', 1, 1, 0, 0);
		},5000);
	}
	//for (xx in object) {
		//console.log(object[xx]['name']+' '+object[xx]['level']+' '+object[xx]['buy_url']);
	//}
}
function pause() {
	run = 0;
	document.getElementById('action').innerHTML = '<a class="sexy_button" id="start">Start</a>';
	msg('Pausing...');
	document.getElementById('start').onclick = start;
}
function start() {
	run = 1;
	var output = '';
	wait1 = parseInt(document.getElementById('wait1').value);
    wait2 = parseInt(document.getElementById('wait2').value);
	document.getElementById('action').innerHTML = '<a class="sexy_button" id="pause">Pause</a>';
	document.getElementById('pause').onclick = pause;
	var theprops = document.getElementsByName('prop');
	for(var i=0; i<theprops.length; i++){
		//levels[i+1] = theprops[i].value;
		levels[i] = theprops[i].value;
	}
	//do_ajax('inner_page', 'remote/html_server.php?xw_controller=property&xw_action=view&xw_city=1', 1, 0, 0, 0);
	buy_next_property();
}
document.getElementById('start').onclick = start;
//document.getElementById('parselog').onclick = parselog;

function parselog() {
    var s = '';
    try { s = document.getElementsByClassName('message_body')[0].innerHTML; }
    catch(ignore) {
		try { s = document.getElementById('msg_box_div_1').innerHTML; }
		catch (ignore2) {}
	}
	if (/You need more cash/.test(s)) {
		run = 0;
		pausemsg = '<span class="bad">You need more cash on hand to continue buying.</span>';
	}
	if (/This property cannot be upgraded/.test(s)) {
		run = 0;
		pausemsg = '<span class="bad">This property cannot be upgraded.</span>';
	}
	if (/Try taking money out of the bank to purchase this/.test(s)) {
		run = 0;
		pausemsg = '<span class="bad">You need more cash on hand to buy properties.</span>';
	}
	//log(timestamp()+s);
	for (x in object) {
		//name level payout rate build_cost upgrade_cost property_pic last_collected percent_collectable buy_url collect_url maxlevel city type
		document.getElementById('proplvl'+x).innerHTML = object[x]['level'];
		document.getElementById('cost'+x).innerHTML = '$'+commas(property_cost(object[x]['level'],document.getElementById('prop'+x).value,object[x]['upgrade_cost'],object[x]['build_cost']));
	}
	document.getElementById('money').innerHTML = '$'+commas(money);
}
function myRandom(min, max) {
	return min + Math.floor(Math.round((Math.random() * (max - min))));
}
// deliberate pause from Vern's toolkit.js, http://vern.com/mwtools/
// given a number of seconds, an optional message and a resume
// function, will pause a few seconds and then execute the function
function pausing(seconds, message, resume_func) {
	// if the message was left out, shuffle things a bit
	if (typeof(message) == 'function') {
		resume_func = message;
		message = null;
	}
	if (message) message = message;
	else message = 'Pausing';
	msg(message + ' <span id="seconds">' + seconds + ' second' + (seconds == 1 ? '' : 's') + '</span>...');
	//var me = this;
	var timer = setInterval(function () { //)
		seconds--;
		if (document.getElementById('seconds')) document.getElementById('seconds').innerHTML = seconds + ' second' + (seconds == 1 ? '' : 's');
		else clearInterval(timer);
		if (seconds <= 0) {
			clearInterval(timer);
			if (typeof(resume_func) == 'function') resume_func();
		}
    },
	1000);
}
function buy_next_property() {
	if (run == 1) {
		for (y in levels) {
			reload_params();
			//alert([y]+' '+object[y]['level']);
			if (object[y]['level'] < levels[y]) {
				var buy_parse = /tmp=([a-fA-F0-9]+).*?cb=([a-z0-9]+).*?building_type=(\d+)/.exec(object[y]['buy_url']);
				var buy_url = 'remote/html_server.php?xw_controller=propertyV2&xw_action=buy&xw_city=1&tmp='+buy_parse[1]+'&cb='+buy_parse[2]+'&building_type='+buy_parse[3];
				//console.log('Buying '+object[y]['name']+' current level: '+object[y]['level']+' wanted level '+levels[y]+' '+buy_url);
				money+=parseInt(object[y]['upgrade_cost']*object[y]['level']+object[y]['build_cost']);
				document.getElementById('inner_page').addEventListener('DOMSubtreeModified',state_change,false);
				do_ajax('inner_page', buy_url, 1, 0);
				failed = 0;
				return;
			}
		}
		run = 0;
		reload_params();
		parselog();
		pause();
		msg('<span class="good">Done upgrading properties...</span>');
	}
	else {
		run = 0;
		reload_params();
		parselog();
		pause();
		if (!pausemsg) { msg('<span class="good">Done upgrading properties...</span>'); }
		else { msg(pausemsg); }
	}
}

function state_change() {
	if(currentPageCount != pageCount) {
		currentPageCount = pageCount;
		document.getElementById('inner_page').removeEventListener('DOMSubtreeModified',state_change,false);
		reload_params();
		setTimeout(parselog, 500);
		var wait = myRandom(wait1,wait2);
        pausing(wait, 'Buying next property in ', buy_next_property);
	}
}
	//for (xx in object) {
		//console.log(object[xx]['name']+' '+object[xx]['level']+' '+object[xx]['buy_url']);
	//}
//end main function
})()

